import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Spin, message, Input } from 'antd';
import axios from 'axios';

const { Search } = Input;

interface Prize {
  id: number;
  prize_name: string;
  prize_description: string;
  prize_image: string;
  points: number;
  stock: number;
}

const StuPrizeList: React.FC = () => {
  const [prizes, setPrizes] = useState<Prize[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [searchText, setSearchText] = useState<string>('');

  useEffect(() => {
    fetchPrizes();
  }, []);

  const fetchPrizes = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/getAllPrizes');
      setPrizes(res.data);
    } catch (error: any) {
      message.error('获取奖品失败: ' + (error?.response?.data?.message || error.message));
    } finally {
      setLoading(false);
    }
  };

  // 过滤函数
  const filteredPrizes = prizes.filter((prize) =>
    prize.prize_name.toLowerCase().includes(searchText.toLowerCase())
  );

  return (
    <div style={{ padding: '40px' }}>
      <h2 style={{ textAlign: 'center', marginBottom: 24 }}>奖品列表</h2>

     {/* 搜索框 */}
<div style={{ textAlign: 'center', marginBottom: 40 }}>
  <Input
    placeholder="搜索奖品名称"
    allowClear
    size="large"
    value={searchText}
    onChange={(e) => setSearchText(e.target.value)}
    style={{ maxWidth: 400, width: '100%' }}
  />
</div>


      {loading ? (
        <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />
      ) : (
       <Row gutter={[24, 24]} align="stretch">
  {filteredPrizes.length > 0 ? (
    filteredPrizes.map((prize) => (
      <Col xs={24} sm={12} md={8} lg={6} key={prize.id} style={{ display: 'flex' }}>
        <Card
          hoverable
          style={{ flex: 1, display: 'flex', flexDirection: 'column', height: '100%' }}
          cover={
            <div style={{ height: 200, overflow: 'hidden' }}>
              <img
                src={`http://localhost:5000${prize.prize_image}`}
                alt={prize.prize_name}
                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              />
            </div>
          }
        >
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
            <Card.Meta
              title={prize.prize_name}
              description={
                <>
                  <p style={{ marginBottom: 4 }}>{prize.prize_description || '暂无描述'}</p>
                  <p style={{ margin: 0 }}>🎁 积分: {prize.points}</p>
                  <p style={{ margin: 0 }}>📦 库存: {prize.stock}</p>
                </>
              }
            />
          </div>
        </Card>
      </Col>
    ))
  ) : (
    <p style={{ textAlign: 'center', width: '100%' }}>未找到匹配的奖品</p>
  )}
</Row>

      )}
    </div>
  );
};

export default StuPrizeList;
